﻿using System;

namespace ConvergentSeries
{
    public delegate decimal NextMemberDelegate(int index);

    class ConvergentSeries
    {

        public decimal FindSum(NextMemberDelegate series)
        {
            decimal Eps = 0.0000001m;
            decimal oldSum = 0;
            decimal sum = 0;
            int index = 0;
            do
            {
                oldSum = sum;
                sum += series(index);
                index++;
            } while (Math.Abs(oldSum - sum) >= Eps);
            return sum;
        }

        static void Main(string[] args)
        {
            ConvergentSeries test = new ConvergentSeries();
            decimal result = test.FindSum((x) => (decimal)Math.Pow(0.5, x));
            Console.WriteLine("{0:F6}", result);

            decimal secondResult = test.FindSum(test.SecondSeries);
            Console.WriteLine("{0}", secondResult);

            decimal thirdResult = test.FindSum(test.ThirdSeries);
            Console.WriteLine("{0}", thirdResult);
        }

        private decimal SecondSeries(int index)
        {
            index++;
            decimal result = 1;
            for (int i = 1; i <= index; i++)
            {
                result /= i;
            }
            return result;

        }

        private decimal ThirdSeries(int index)
        {
            if (index == 0) return 1;
            decimal result = (decimal)Math.Pow(-1, (index + 1) % 2);
            result /= (decimal)Math.Pow(2, index);
            return result;
        }
    }
}
